<!-- src/views/UserManagement.vue -->
<template>
  <div class="container">
    <div class="header">
      <h2>用户管理</h2>
      <button class="btn btn-outline-secondary" @click="goHome">
        返回主页
      </button>
    </div>

    <div class="card">
      <div class="card-header">
        <h5>用户列表</h5>
      </div>
      <div class="card-body">
        <div class="btn-group">
          <button class="btn" @click="loadUsers">刷新列表</button>
          <button class="btn btn-success" @click="showAddUserForm">
            添加用户
          </button>
        </div>

        <div id="userList">
          <div v-if="loading" class="text-center">
            <div class="spinner"></div>
            <p>加载中...</p>
          </div>
          <div v-else-if="users.length === 0" class="text-muted text-center">
            暂无用户数据
          </div>
          <div v-else class="table-responsive">
            <table>
              <thead>
              <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>邮箱</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
              </thead>
              <tbody>
              <tr v-for="user in users" :key="user.id">
                <td>{{ user.id }}</td>
                <td>{{ user.userName }}</td>
                <td>{{ user.email || "" }}</td>
                <td>
                    <span
                        :class="user.isDelete == 0 ? 'bg-success' : 'bg-danger'"
                        class="badge"
                    >
                      {{ user.isDelete == 0 ? "启用" : "禁用" }}
                    </span>
                </td>
                <td>
                  <button
                      class="btn btn-sm btn-outline-primary"
                      @click="editUser(user.id)"
                  >
                    编辑
                  </button>
                  <button
                      class="btn btn-sm btn-outline-danger"
                      @click="deleteUser(user.id)"
                  >
                    删除
                  </button>
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑用户模态框 -->
    <modal :show="showModal" @close="closeModal">
      <template #header>
        <h5 class="modal-title">{{ modalTitle }}</h5>
      </template>
      <template #body>
        <form id="userForm">
          <input
              v-if="editingUser.id"
              id="userId"
              v-model="editingUser.id"
              type="hidden"
          />
          <div class="form-group">
            <label class="form-label" for="userName">用户名</label>
            <input
                id="userName"
                v-model="editingUser.userName"
                class="form-control"
                required
                type="text"
            />
          </div>
          <div class="form-group">
            <label class="form-label" for="email">邮箱</label>
            <input
                id="email"
                v-model="editingUser.email"
                class="form-control"
                required
                type="email"
            />
          </div>
          <div class="form-group">
            <label class="form-label" for="password">密码</label>
            <input
                id="password"
                v-model="editingUser.password"
                class="form-control"
                type="password"
            />
            <div class="form-text">编辑用户时留空表示不修改密码</div>
          </div>
          <div class="form-group">
            <label class="form-label" for="isDelete">状态</label>
            <select
                id="isDelete"
                v-model="editingUser.isDelete"
                class="form-control"
            >
              <option value="0">启用</option>
              <option value="1">禁用</option>
            </select>
          </div>
        </form>
      </template>
      <template #footer>
        <button
            class="btn btn-outline-secondary"
            type="button"
            @click="closeModal"
        >
          取消
        </button>
        <button class="btn" type="button" @click="saveUser">保存</button>
      </template>
    </modal>

    <!-- 添加消息提示组件 -->
    <message ref="messageComponent"/>
  </div>
</template>

<script>
import Modal from "@/components/Modal.vue";
import Message from "@/components/Message.vue";
import {addUser, deleteUser, getAllUsers, getUserById, getUserInfo, updateUserInfo,} from "@/utils/api.js";

export default {
  name: "UserManagement",
  components: {
    Modal,
    Message,
  },
  data() {
    return {
      loading: true,
      users: [],
      showModal: false,
      modalTitle: "添加用户",
      editingUser: {
        id: null,
        userName: "",
        email: "",
        password: "",
        isDelete: 0,
      },
    };
  },
  mounted() {
    this.checkLoginAndLoadUsers();
  },
  methods: {
    async checkLoginAndLoadUsers() {
      try {
        const response = await getUserInfo();
        if (response && response.success && response.data) {
          // 已登录，加载用户列表
          this.loadUsers();
        } else {
          this.$refs.messageComponent.show(
              "获取用户信息失败: " + (response ? response.message : "未知错误"),
              "danger",
          );
        }
      } catch (error) {
        console.error("检查登录状态失败:", error);
        this.$refs.messageComponent.show(
            "检查登录状态失败: " + error.message,
            "danger",
        );
      }
    },
    async loadUsers() {
      this.loading = true;
      try {
        const response = await getAllUsers();
        if (response.success) {
          this.users = response.data;
        } else {
          this.$refs.messageComponent.show(
              "获取用户列表失败: " + response.message,
              "danger",
          );
        }
      } catch (error) {
        console.error("获取用户列表失败:", error);
        this.$refs.messageComponent.show(
            "获取用户列表失败: " + error.message,
            "danger",
        );
      } finally {
        this.loading = false;
      }
    },
    showAddUserForm() {
      this.modalTitle = "添加用户";
      this.editingUser = {
        id: null,
        userName: "",
        email: "",
        password: "",
        isDelete: 0,
      };
      this.showModal = true;
    },
    closeModal() {
      this.showModal = false;
    },
    async editUser(userId) {
      try {
        const response = await getUserById({id: userId});
        if (response.success) {
          this.modalTitle = "编辑用户";
          this.editingUser = {...response.data, password: ""};
          this.showModal = true;
        } else {
          this.$refs.messageComponent.show(
              "获取用户信息失败: " + response.message,
              "danger",
          );
        }
      } catch (error) {
        this.$refs.messageComponent.show(
            "获取用户信息失败: " + error.message,
            "danger",
        );
      }
    },
    async saveUser() {
      const {id, userName, email, password, isDelete} = this.editingUser;

      // 验证必填字段
      if (!userName) {
        this.$refs.messageComponent.show("用户名不能为空", "danger");
        return;
      }

      if (!email) {
        this.$refs.messageComponent.show("邮箱不能为空", "danger");
        return;
      }

      const userData = {
        userName,
        email,
        isDelete: parseInt(isDelete),
      };

      // 添加用户时密码是必需的
      if (!id) {
        if (!password) {
          this.$refs.messageComponent.show("密码不能为空", "danger");
          return;
        }
        userData.password = password;
      } else if (password) {
        // 编辑用户时，如果填写了密码则更新密码
        userData.password = password;
      }

      try {
        const response = id
            ? await updateUserInfo(userData)
            : await addUser(userData);

        if (response.success) {
          this.closeModal();
          // 显示成功消息
          this.$refs.messageComponent.show("用户保存成功", "success");
          // 重新加载用户列表
          this.loadUsers();
        } else {
          this.$refs.messageComponent.show(
              "保存用户失败: " + response.message,
              "danger",
          );
        }
      } catch (error) {
        this.$refs.messageComponent.show(
            "保存用户失败: " + error.message,
            "danger",
        );
      }
    },
    async deleteUser(userId) {
      if (confirm("确定要删除用户 ID: " + userId + " 吗？")) {
        try {
          const response = await deleteUser({id: userId});
          if (response.success) {
            // 显示成功消息
            this.$refs.messageComponent.show("用户删除成功", "success");
            // 重新加载用户列表
            this.loadUsers();
          } else {
            this.$refs.messageComponent.show(
                "删除用户失败: " + response.message,
                "danger",
            );
          }
        } catch (error) {
          this.$refs.messageComponent.show(
              "删除用户失败: " + error.message,
              "danger",
          );
        }
      }
    },
    goHome() {
      this.$router.push("/");
    },
  },
};
</script>

<!-- 在<style>标签中修改路径 -->
<style scoped>
@import "../assets/css/pages/users.css";
</style>
